#include "command.h"

void command_cd(command_t *cod, int netFD, MYSQL *conn, client_t *clt){
    //cd ..  cd dir
    if(strcmp(cod->path, "..") == 0){
        //返回上一级目录
        char buf1[1024] = { 0 };
        sprintf(buf1, "select id, path from file where id = "
                "(select father_id from file where id = %d)", clt->file_id);
        if (mysql_query(conn, buf1)) {
            printf("%s\n", mysql_error(conn));
            return;
        }
        MYSQL_RES *result;
        MYSQL_ROW row;
        result = mysql_store_result(conn);
        if(!result || (mysql_num_rows(result) == 0)){
            mysql_free_result(result);
            //不存在上级目录
            int ret = -1;
            send(netFD, &ret, sizeof(ret), MSG_NOSIGNAL);
            return;
        }
        row = mysql_fetch_row(result);
        clt->file_id = atoi(row[0]);
        bzero(clt->dir_path, sizeof(clt->dir_path));
        strcpy(clt->dir_path, row[1]);
        mysql_free_result(result);
        //存在上一级目录
        int ret = 0;
        send(netFD, &ret, sizeof(ret), MSG_NOSIGNAL);
        send(netFD, clt, sizeof(clt), MSG_NOSIGNAL);
    }else{
        char path[1024] = { 0 };
        sprintf(path, "%s/%s", clt->dir_path, cod->path);
        char buf1[1024] = { 0 };
        sprintf(buf1, "select id from file where path = %s and user_name = %s", path, clt->name);
        if (mysql_query(conn, buf1)) {
            printf("%s\n", mysql_error(conn));
            return;
        }
        MYSQL_RES *result;
        MYSQL_ROW row;
        result = mysql_store_result(conn);
        if(!result || (mysql_num_rows(result) == 0)){
            mysql_free_result(result);
            //说明输入的路径不对
            //需要重新输入
            int ret = -1;
            send(netFD, &ret, sizeof(ret), MSG_NOSIGNAL);
            return;
        }
        row = mysql_fetch_row(result);
        clt->file_id = atoi(row[0]);
        bzero(clt->dir_path, sizeof(clt->dir_path));
        strcpy(clt->dir_path, path);
        mysql_free_result(result);
        int ret = 0;
        send(netFD, &ret, sizeof(ret), MSG_NOSIGNAL);
        send(netFD, clt, sizeof(clt), MSG_NOSIGNAL);
    }
}
